import React from 'react'
import _ from 'lodash'
import { Table } from 'antd'
import { TwsReactMarkdownPreview } from 'tws-antd'
import { FormattedMessage } from 'react-intl'

export default class AssignmentsSurveyQuizzesStatusBox extends React.Component {

  getQuizChoices = assignmentsSurveyQuizzesOverview => {
    return assignmentsSurveyQuizzesOverview.filter(item => item.description === assignmentsSurveyQuizzesOverview[0].description)
  }
  getColumns = assignmentsSurveyQuizzesOverview => {
    const currentQuizChoices = this.getQuizChoices(assignmentsSurveyQuizzesOverview)
    let columns = [{
      title: <FormattedMessage id='题目'/>,
      dataIndex: 'description',
      render: text => <a href='javascript:(0)'>{(text || '').substring(0, 80)}</a>
    }, {
      title: <FormattedMessage id='总人数'/>,
      dataIndex: 'total'
    }, {
      title: <FormattedMessage id='已提交人数'/>,
      dataIndex: 'totalSubmitted',
      sorter: (a, b) => a.totalSubmitted - b.totalSubmitted
    }]
    currentQuizChoices.forEach(item => {
      columns.push({
        title: item.choice,
        dataIndex: item.choice,
        render: (text, record) => {
          return text > 0
            ? parseInt((text / record.totalSubmitted).toFixed(2) * 100) + '%'
            : '0%'
        }
      })
    })
    return columns
  }

  statistic = (current, description) => {
    let groupByUsernameQuizzes = _.groupBy(current, item => item.userName)
    const choices = Object.keys(_.groupBy(current, item => item.choice))
    const total = Object.keys(groupByUsernameQuizzes).length
    const totalSubmitted = Object.keys(groupByUsernameQuizzes)
      .filter(item => !!groupByUsernameQuizzes[item][0].userAnswer).length

    let result = {total, totalSubmitted, description}
    choices.forEach((choice, index) => {
      result[choice] = Object.keys(groupByUsernameQuizzes)
        .filter(item => parseInt(groupByUsernameQuizzes[item][0].userAnswer) === index).length
    })
    return result
  }
  getData = assignmentsSurveyQuizzesOverview => {
    const result = []
    const data = _.groupBy(assignmentsSurveyQuizzesOverview, item => item.description)

    Object.keys(data).forEach(key => {
      const currentQuiz = data[key]
      result.push(this.statistic(currentQuiz, key))
    })
    result.sort((a, b) => b.correctCount - a.correctCount)
    return result
  }

  render () {
    const {assignmentsSurveyQuizzesOverview} = this.props
    const columns = this.getColumns(assignmentsSurveyQuizzesOverview)
    const data = this.getData(assignmentsSurveyQuizzesOverview)

    return <Table columns={columns}
                  dataSource={data}
                  pagination={false}
                  bordered
                  size='small'
    />
  }
}